'''def split_file(filename, chunk_size):
    with open(filename, 'rb') as file:
        index = 0
        chunk = file.read(chunk_size)
        while chunk:
            with open(f"{filename}.{chunk_size}.{index}", 'wb') as chunk_file:
                chunk_file.write(chunk)
                index += 1
                chunk = file.read(chunk_size)
split_file("D:/eeeeeeeee/小智桌面_3.0.0.32_Setup.zip",4000000)
'''

# !/home/***/anaconda3/bin/python #选择合适的python版本
"""
    xpan upload
    include:
        precreate
        upload
        create
"""
import os
import sys

BASE_DIR = os.path.dirname ( os.path.dirname ( os.path.abspath ( __file__ ) ) )
sys.path.append ( BASE_DIR )
from pprint import pprint
from openapi_client.api import fileupload_api
import openapi_client
import hashlib


def precreate () :
    """
    precreate
    """
    #    Enter a context with an instance of the API client
    with openapi_client.ApiClient ( ) as api_client :
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi ( api_client )
        access_token = "126.c56c6366595dcc417c8a2c0a99e735b2.YmiHXOj071iMcLnenlTyExzPJiZ0ZBb3Xn0qS4Q.xevO2w" # 填入自己的access_token
        path = "/apps/text/eeeeeeeee"  # str | 对于一般的第三方软件应用，路径以 "/apps/your-app-name/" 开头。对于小度等硬件应用，路径一般 "/来自：小度设备/" 开头。对于定制化配置的硬件应用，根据配置情况进行填写。

        block_list = ''
        file_path = "D:/eeeeeeeee/"  # 要上传的文件的真实路径
        '''
        with open ( file_path , 'rb' ) as f :
            data = f.read ( )
            file_md5 = hashlib.md5 ( data ).hexdigest ( )  # 获取上传文件md5
            block_list = block_list + '["{}"]'.format ( file_md5 )  # 放入block_list
            print ( block_list )'''

        size = os.path.getsize ( file_path )  # 获取上传文件大小
        print ( size )

        isdir = 1  # int | isdir
        autoinit = 1  # int | autoinit
        rtype = 3  # int | rtype (optional)

        try :
            api_response = api_instance.xpanfileprecreate ( access_token , path , isdir , size , autoinit , block_list , rtype = rtype )
            pprint ( api_response )
            uploadid = api_response [ 'uploadid' ]  # 获取预上传返回的uploadid，传给upload和create函数
        except openapi_client.ApiException as e :
            print ( "Exception when calling FileuploadApi->xpanfileprecreate: %s\n" % e )
        return access_token , path , isdir , size , uploadid , block_list , rtype , file_path


def upload ( uploadid , path , file_path , access_token ) :
    """
    upload
    """
    # Enter a context with an instance of the API client
    with openapi_client.ApiClient ( ) as api_client :
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi ( api_client )

        chunk_size = 4 * 1024 * 1024
        with open ( file_path , 'rb' ) as f :
            if size > chunk_size :
                index = 0
                chunk = f.read ( chunk_size )
                while chunk :
                    with open ( f"{file_path}.{chunk_size}.{index}" , 'wb' ) as chunk_file :
                        chunk_file.write ( chunk )
                        index += 1
                        chunk = f.read ( chunk_size )

        partseq = "0"  # str |
        type = "tmpfile"  # str |
        try :
            folder_path = "D:/eeeeeeeee/temp/"
            if not os.path.exists ( folder_path ) :
                os.makedirs ( folder_path )
            block_list = '['
            for file_name in os.listdir ( folder_path ) :
                file_path_temp = os.path.join ( folder_path , file_name )
                print ( file_path_temp )
                with open ( file_path_temp , 'rb' ) as f :
                    data = f.read ( )
                    file_md5 = hashlib.md5 ( data ).hexdigest ( )  # 获取上传文件md5
                    block_list += '"{}",'.format ( file_md5 )  # 放入block_list
            block_list = block_list [ :-1 ] + "]"
            print(block_list)

            # example passing only required values which don't have defaults set
            # and optional values
            try :
                api_response = api_instance.pcssuperfile2 ( access_token , partseq , path , uploadid , type , file = file_path_temp )
                pprint ( api_response )
            except openapi_client.ApiException as e :
                print ( "Exception when calling FileuploadApi->pcssuperfile2: %s\n" % e )



            #file = open ( file_path , 'rb' )
        except Exception as e :
            print ( "Exception when open file: %s\n" % e )
            exit ( -1 )




def create ( access_token , path , isdir , size , uploadid , block_list , rtype ) :
    """
    create
    """
    # Enter a context with an instance of the API client
    with openapi_client.ApiClient ( ) as api_client :
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi ( api_client )

        # example passing only required values which don't have defaults set
        # and optional values
        try :
            api_response = api_instance.xpanfilecreate ( access_token , path , isdir , size , uploadid , block_list , rtype = rtype )
            pprint ( api_response )
        except openapi_client.ApiException as e :
            print ( "Exception when calling FileuploadApi->xpanfilecreate: %s\n" % e )


if __name__ == '__main__' :
    access_token , path , isdir , size , uploadid , block_list , rtype , file_path = precreate ( )
    upload ( uploadid , path , file_path , access_token )
    #create ( access_token , path , isdir , size , uploadid , block_list , rtype )
